﻿
using ERPSystem.Common.Domains.UserCommon;
using ERPSystem.Common.DTO;
using ERPSystem.Common.Infrastructure.IRepository;
using ERPSystem.Enum.CommonErrorCodes;
using MediatR;

namespace RBACCommon.API.Command.Permissions
{
    public class PermissionCascaderHandler : IRequestHandler<PermissionCascaderCommon, Result<List<PermissionCascaderDto>>>
    {
        private readonly IBaseRepository<Permission> permissionRep;
        public PermissionCascaderHandler(IBaseRepository<Permission> _permissionRep)
        {
            permissionRep = _permissionRep;
        }
        public async Task<Result<List<PermissionCascaderDto>>> Handle(PermissionCascaderCommon request, CancellationToken cancellationToken)
        {
            var result = new Result<List<PermissionCascaderDto>>() { Code = (int)CommonErrorCode.Search };
            var list = await (await permissionRep.GetAll()).Where(c => c.PerantId == 0).ToListAsync();
            List<PermissionCascaderDto> permissionCascaderDtos = new List<PermissionCascaderDto>();
            foreach (var item in list)
            {
                PermissionCascaderDto permissionCascaderDto = new PermissionCascaderDto();
                permissionCascaderDto.label = item.PermissionsName;
                permissionCascaderDto.value = item.PermissionsId;
                permissionCascaderDto.children = await Cascader(item.PermissionsId);
                permissionCascaderDtos.Add(permissionCascaderDto);
            }
            result.Data = permissionCascaderDtos;
            return result;
        }
        public async Task<List<PermissionCascaderDto>> Cascader(int parentId)
        {
            var list = await (await permissionRep.GetAll()).Where(c => c.PerantId == parentId).ToListAsync();
            List<PermissionCascaderDto> permissionCascaderDtos = new List<PermissionCascaderDto>();
            foreach (var item in list)
            {
                PermissionCascaderDto permissionCascaderDto = new PermissionCascaderDto();
                permissionCascaderDto.label = item.PermissionsName;
                permissionCascaderDto.value = item.PermissionsId;
                permissionCascaderDto.children = await Cascader(item.PermissionsId);
                permissionCascaderDtos.Add(permissionCascaderDto);
            }

            return permissionCascaderDtos;
        }
    }
}
